package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.InsuranceOrder;
import cn.wolfcode.trip.base.domain.InsuranceProduct;
import cn.wolfcode.trip.base.query.InsuranceQuery;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IInsuranceOrderService;
import cn.wolfcode.trip.base.service.IInsuranceProductService;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 保险产品资源控制器
 */
@RestController
@RequestMapping("insurances")
public class InsuranceController {
    @Autowired
    private IInsuranceProductService insuranceProductService;
    @Autowired
    private IInsuranceOrderService insuranceOrderService;
    @Autowired
    private IRegionService regionService;

    /**
     * 查询所有保险产品
     *
     * @param qo
     * @return
     */
    @GetMapping("list")
    public PageInfo listProducts(InsuranceQuery qo) {
        // 修改为 非禁用状态
        qo.setState(InsuranceProduct.STATE_NOMAL);

        // 按照创建时间倒序
        qo.setOrderBy("createTime DESC");
        // 分页查询
        PageInfo pageInfo = insuranceProductService.queryForShows(qo);
        return pageInfo;
    }


    /**
     * 查询推荐的保险产品（state!=-1）
     *
     * @return
     */
    @GetMapping("commends")
    public PageInfo listCommends(InsuranceQuery qo) {
        //按照创建时间倒序
        qo.setOrderBy("createTime desc");
        PageInfo pageInfo = insuranceProductService.queryForApp(qo);
        return pageInfo;
    }

    /**
     * 选定并进入某一保险产品页面，查询此产品信息
     * id
     *
     * @return
     */
    @GetMapping("/products/{id}")
    public InsuranceProduct getDetailsById(@PathVariable Long id) {
        InsuranceProduct insuranceProduct = insuranceProductService.getProductById(id);
        return insuranceProduct;
    }

    /**
     * 判断用户钱包余额是否充足，充足则提交保存订单，否则就提示用户余额不足
     *
     * @param insuranceOrder
     * @return
     */
    @PostMapping("/{userId}")
    public JSONResult save(InsuranceOrder insuranceOrder, @PathVariable Long userId) {
        JSONResult jsonResult = new JSONResult();
        // 为获取提交订单成功或失败的两个方面信息，需要在余额不足时创建运行异常，并将余额不足信息传递到页面提示用户
        // <余额充足时直接扣款保存订单，不用提示>
        try {
            insuranceOrderService.save(insuranceOrder, userId);
        } catch (Exception e) {
            e.printStackTrace();
            // 把钱包余额不足提示信息封装到JSONResult中，方便页面获取提示用户
            jsonResult.mark(e.getMessage());
        }
        return jsonResult;
    }

    /**
     * 查询所有的保险订单
     *
     * @return
     */
    @GetMapping("orders")
    public PageInfo listOrders(QueryObject qo) {
        //按照创建时间倒序
        qo.setOrderBy("orderTime desc");
        PageInfo pageInfo = insuranceOrderService.queryForOrders(qo);
        return pageInfo;
    }


}
